<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise模拟远程用户登录</title>
</head>
<body>
<script>
    //1 模拟数据源
    const users = [{ username: 'user1', password: 'password1' }, { username: 'user2', password: 'password2' }];
    //2 模拟登录验证
    function auth(username,password){
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                const user = users.find(user=>user.username===username&&user.password===password);
                if(user){
                    resolve(user);
                }else{
                    reject('用户名或密码有误');
                }
            },2000);
        });
    };

    auth('user1', 'password1').then((user)=>{
        console.log(`Welcome, ${user.username}!`);
    },(error)=>{
        console.error(error.message);
    });
</script>
</body>
</html>